package com.kuanter.kuanterauto.activity;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.City;
import com.kuanter.kuanterauto.entity.KuanterService;
import com.kuanter.kuanterauto.entity.Restrictions;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.entity.VehicleInfoList;
import com.kuanter.kuanterauto.entity.WearherInfo;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.net.HttpUtil;
import com.kuanter.kuanterauto.utils.AnimationController;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.JsonParser;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;

/**
 * 主页面服务展示
 * @author kuanter
 *
 */
public class ServicesActivity extends BaseActivity_NoBar {
	public static boolean NocticeShow = false;
	
	public static int noticeDayInsurance = 5;
	public static int noticeDayYearCharge = 90;
	
	List<String> noticeAll = new ArrayList<String>();
	
	GridView allServices;   //所有洗车服务
	LayoutInflater factory;
	AllServiceAdapter serviceAdapter;
	
	boolean goToSite = false;
	
	RelativeLayout middle_weather_road; 
//	RelativeLayout w_bg;  //设置天气的背景图片
	
	TextView mCityName;
	String city;
	TextView mCityID;
	String city_ID;
	
	LinearLayout home_chose_City; //点击选择城市
	
	ImageView forbid_img;
	
	public static int request_city = 0;
	
	List<KuanterService> kuanter = new ArrayList<KuanterService>();
	
	ProApplication application;
	
	List<City> cityList;
	
	String lc_front = "";  //截取2位后的定位城市
//	String chose_front = "";  //截取2位后保存的当前城市
	List<KuanterService> map = new ArrayList<KuanterService>();   //记录点击的服务
	
	static Restrictions restriction;  //限行信息
	
	/*
	 * 获取限行信息的hanlder
	 */
	Handler restri_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				Log.i("bbb", json + "限行");
				restriction = JsonParser.getRestri(json);
				if(restriction != null) {
//					if(dialog != null) {
//						res_time.setText(restriction.getdRTime() + "");
//						region.setText(restriction.getdRRegion() + "");
//						rule.setText(restriction.getdRRule() + "");
//						dialog.show();
//					}
					if(restriction.getdRRegion() != null && !restriction.getdRRegion().equals("")) {
						forbid_img.setVisibility(View.VISIBLE);
					} else {
						forbid_img.setVisibility(View.GONE);
					}
					
					if(restriction.getdRNumber() != null && !restriction.getdRNumber().equals("")) {
						lin_xxwh.setVisibility(View.VISIBLE);
						xxwh.setText(restriction.getdRNumber());
					} else {
						lin_xxwh.setVisibility(View.GONE);
					}
					
				} else {
//					showToast("暂无限行信息");
					forbid_img.setVisibility(View.GONE);
					lin_xxwh.setVisibility(View.GONE);
				}
			}
			super.handleMessage(msg);
		}
		
	};
	
	/*
	 * 获取服务列表
	 */
	Handler h = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				kuanter = JsonParser.getKuanterService(json);
				List<KuanterService> app = new ArrayList<KuanterService>();
				app.addAll(kuanter);
				application.setList_kuanterService(app);  
				if(kuanter != null) {
					
					KuanterService chongzhi = new KuanterService();
					chongzhi.setServiceType("充值");
					chongzhi.setServiceID(MainConstants.CZ);
					kuanter.add(chongzhi);
					
					KuanterService jh = new KuanterService();
					jh.setServiceID(MainConstants.JH);
					jh.setServiceType("激活");
					kuanter.add(jh);
					
					KuanterService cx = new KuanterService();
					cx.setServiceType("车险");
					cx.setServiceID(MainConstants.CX);
					kuanter.add(cx);
					
					KuanterService lc = new KuanterService();
					lc.setServiceType("理财");
					lc.setServiceID(MainConstants.LC);
					kuanter.add(lc);
				} 
				finishProgress();
				serviceAdapter.notifyDataSetChanged();
			} else if(msg.what == ProApplication.location_cuccess) {
				city = SharePrefenceUtil.getCity(ServicesActivity.this);
				lc_front= (String) msg.obj;
				
				//跳转到网点列表
				if(goToSite) {
					String chosed_city = mCityName.getText().toString();
					KuanterService service = map.get(0);
					String str = service.getList_service().get(0).getServiceName();
					if(!lc_front.equals("")) {
						if(!lc_front.equals(chosed_city)) {
							
							String typeID = service.getServiceID();
							String serviceID = service.getList_service().get(0).getServiceID();
							Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
							intent.putExtra("service", str);
							intent.putExtra("typeID", typeID);
							intent.putExtra("serviceID", serviceID);
							intent.putExtra("localCity", false);
							intent.putExtra("cityName", chosed_city);
							startActivity(intent);
							
						} else {
							
							String typeID = service.getServiceID();
							String serviceID = service.getList_service().get(0).getServiceID();
							Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
							intent.putExtra("service", str);
							intent.putExtra("typeID", typeID);
							intent.putExtra("serviceID", serviceID);
							intent.putExtra("cityName", chosed_city);
							startActivity(intent);
						}
					} 
					goToSite = false;
					map.clear();
					finishProgressLocation();
				}
				
				
				if(!lc_front.equals(mCityName.getText().toString()) && !lc_front.equals("")) {
					//获取城区和什么...TODO
					
					if(ServicesActivity.this != null) {
						
						new AlertDialog.Builder(ServicesActivity.this)
						.setTitle("切换城市").setMessage("GPS定位到您当前在" + lc_front + ",需要切换吗?")
						.setPositiveButton("切换", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								try {
									FileInputStream fis = openFileInput("cityList");
									byte[] bytes = new byte[1024];
									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									while(fis.read(bytes) != -1) {
										baos.write(bytes,0,bytes.length);
									}
									fis.close();
									baos.close();
									String json = new String(baos.toByteArray());
									cityList = JsonParser.getCitys(json);
								} catch (FileNotFoundException e) {
									e.printStackTrace();
									cityList = City.getCitys(ServicesActivity.this);
								} catch (IOException e) {
									e.printStackTrace();
									cityList = City.getCitys(ServicesActivity.this);
								}
								
								for(int i = 0; i < cityList.size(); i++) {
									City mCity = cityList.get(i);
									String cityName = mCity.getCityName();
									if(cityName.length() >= 2) {
										String str = cityName.substring(0, 2);
										if(str.equals(lc_front)) {
											String cityCode = mCity.getCityID();
											//发送请求  TODO  
											int k = 0;
											break;
										}
									}
								}
								
							}
						}).setNegativeButton("取消", null);
//						.create().show();
						
					}
				}
			} else if(msg.what == HttpTask.RESULT_ERROR) {
				showToast("获取数据失败,请稍后再试");
				kuanter = null;
				serviceAdapter.notifyDataSetChanged();
				finishProgress();
			}
			super.handleMessage(msg);
		}
		
	};
	
	
	static WearherInfo wea_info = null;
//	String wea_temp;
	Handler wea_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				wea_info = JsonParser.getWeatherInfo(json);
				if (wea_info != null) {
					weather_tq.setText(wea_info.getTq_info());
					// ---
					if (wea_info.getXc_number() != null) {
						xczs.setText(wea_info.getXc_number());
						if (wea_info.getXc_number().equals(WearherInfo.bsy)
								|| wea_info.getXc_number().equals(
										WearherInfo.jbsy)) {
							xczs.setTextColor(Color.WHITE);
						} else {
							xczs.setTextColor(Color.GREEN);
						}
					}
					// ----
					middle_weather_road.setBackgroundResource(wea_info
							.getImgRes());
					weather_temp.setText(wea_info.getTemp() + "°");
				}
			}
			super.handleMessage(msg);
		}

	};
	
	int status = 0;
	int arg_week = 100;
	int arg_day = 101;
	
	LinearLayout lin_xxwh; //限行尾号
	TextView xxwh;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (ProApplication) getApplication();
		setContentView(R.layout.service);
		factory = getLayoutInflater();
		forbid_img = (ImageView) findViewById(R.id.forbid_img);
		forbid_img.setVisibility(View.GONE);
		
		lin_xxwh = (LinearLayout) findViewById(R.id.lin_xxwh);
		xxwh = (TextView) findViewById(R.id.xxwh);
		lin_xxwh.setVisibility(View.GONE);
		
		if(restriction == null) {
			//获取限行信息
			DataLoader loader = new DataLoader(ServicesActivity.this);
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			NameValuePair cityID = new BasicNameValuePair("cityCode",SharePrefenceUtil.getCityID(ServicesActivity.this));
			params1.add(cityID);
			//TODO
			loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.findRestriction, params1, restri_handler, "", false);
		} else {
			
//			forbid_img.setVisibility(View.VISIBLE);
//			lin_xxwh.setVisibility(View.VISIBLE);
//			xxwh.setText(restriction.getdRNumber());
			
			if(restriction.getdRRegion() != null && !restriction.getdRRegion().equals("")) {
				forbid_img.setVisibility(View.VISIBLE);
			} else {
				forbid_img.setVisibility(View.GONE);
			}
			if(restriction.getdRNumber() != null && !restriction.getdRNumber().equals("")) {
				lin_xxwh.setVisibility(View.VISIBLE);
				xxwh.setText(restriction.getdRNumber());
			} else {
				lin_xxwh.setVisibility(View.GONE);
			}
		}
		
		//获取天气
//		DataLoader loader_wea = new DataLoader(ServicesActivity.this);
//		String url_wea = "http://m.weather.com.cn/data/101200101.html";
//		loader_wea.DisplayData(url_wea, new ArrayList<NameValuePair>(), wea_handler, "", false);
		if(wea_info == null) {
			String cityforweatherID = SharePrefenceUtil.getCityIDForWeather(ServicesActivity.this);
			DataLoader loadWeather = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair nvp = new BasicNameValuePair("cityId",cityforweatherID);
			params.add(nvp);
			loadWeather.DisplayData(MainConstants.HOST_test + HttpConfigAPI.FINDCITYWEATHER, params, wea_handler, "", false);
//			new Thread(new WeaRun("http://m.weather.com.cn/data/" + cityforweatherID + ".html",arg_week)).start();
//			new Thread(new WeaRun("http://www.weather.com.cn/data/sk/" + cityforweatherID + ".html",arg_day)).start();
		}
		
		//用户已登录则判断车险是否过期
		if(SharePrefenceUtil.checkLogin(ServicesActivity.this)) {
			if(application.getList_vehicleInfo() == null || application.getList_vehicleInfo().size() == 0) {
				DataLoader loader_car = new DataLoader(ServicesActivity.this);
				String url_car = MainConstants.HOST_test + HttpConfigAPI.FINDVEHICLE;
				List<NameValuePair> list_car = new ArrayList<NameValuePair>();
				NameValuePair params_car = new BasicNameValuePair("vehicleInfo.userId", SharePrefenceUtil.getUserID(ServicesActivity.this) + "");
				list_car.add(params_car);
				loader_car.DisplayData(url_car, list_car, mHandlerVie, "", false);
			} else {
				for(int i = 0; i < application.getList_vehicleInfo().size(); i++) {
					VehicleInfo vi = application.getList_vehicleInfo().get(i);
					String endTime_insurance = vi.getInsuranceEndTime();
					if(checkWetherExpire(endTime_insurance,noticeDayInsurance)) {
						noticeAll.add("车" + vi.getLicensePlateNumber());
					}
					
					String endTime_yearChager = vi.getInspectionExpireTime();
					if(checkWetherExpire(endTime_yearChager, noticeDayYearCharge)) {
						noticeAll.add("年" + vi.getLicensePlateNumber());
					}
				}
				new Thread(run_ad).start();
			}
		}
		
		initWeather();
		
		initView();
		if(ProApplication.loc_city.equals("")) {
			/*h.postDelayed(new Runnable() {
				@Override
				public void run() {
					application.startRequest(h);
				}
			}, 20000);*/
			application.startRequest(h);
		} else {
			lc_front = ProApplication.loc_city;
		}
		
		/*h.postDelayed(new Runnable() {
			@Override
			public void run() {
				application.startRequest(h);
			}
		}, 2500);*/
		
	}
	
	
	TextView weather_temp;
	TextView weather_tq;
	TextView xczs;  //洗车指数
	
	LinearLayout lin_cx_ad;
	ImageView deleteit;
	TextView first_ad;
	TextView next_ad;
	
	View xxxx;  //限行信息;
	TextView rule;
	TextView region;
	TextView res_time;
	
	Dialog dialog;  //限行消息
	private void initWeather() {
		weather_temp = (TextView) findViewById(R.id.weather_temp);
		weather_tq = (TextView) findViewById(R.id.weather_tq);
		middle_weather_road = (RelativeLayout) findViewById(R.id.middle_weather_road);
		xczs = (TextView) findViewById(R.id.xczs);
		if(wea_info != null) {
			weather_temp.setText(wea_info.getTemp() + "°");
			weather_tq.setText(wea_info.getTq_info());
			middle_weather_road.setBackgroundResource(wea_info.getImgRes());
			xczs.setText(wea_info.getXc_number());
			if(wea_info.getXc_number().equals(WearherInfo.bsy) || wea_info.getXc_number().equals(WearherInfo.jbsy)) {
				xczs.setTextColor(Color.WHITE);
			} else {
				xczs.setTextColor(Color.GREEN);
			}
		}
		//TODO
		forbid_img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				xxxx = factory.inflate(R.layout.restriction, null);
				rule = (TextView) xxxx.findViewById(R.id.rule);
				region = (TextView) xxxx.findViewById(R.id.region);
				res_time = (TextView) xxxx.findViewById(R.id.res_time);
				dialog = new Dialog(ServicesActivity.this,R.style.selectorDialog);
				dialog.setTitle("限行信息");
				dialog.setContentView(xxxx);
				if(restriction == null) {
					showProgress("正在获取限行信息...");
					DataLoader loader = new DataLoader(ServicesActivity.this);
					List<NameValuePair> params1 = new ArrayList<NameValuePair>();
					NameValuePair cityID = new BasicNameValuePair("cityCode",SharePrefenceUtil.getCityID(ServicesActivity.this));
					params1.add(cityID);
					//TODO
					loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.findRestriction, params1, restri_handler, "", false);
				} else {
					rule.setText(restriction.getdRRule() + "");
					region.setText(restriction.getdRRegion() + "");
//					res_time.setText(restriction.getdRTime() + "");
					dialog.show();
				}
				
			}
		});
		
	}
	
	//--------------------------
	int i = 0;   //notice标记
	boolean falg = true;
	Runnable run_ad = new Runnable() {
		@Override
		public void run() {
			while(falg) {
				
				if(!NocticeShow) {
					for (int i = 0; i < noticeAll.size(); i++) {
						if(falg) {
							ad_handler.sendEmptyMessage(i);
							try {
								Thread.sleep(5000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
					if(falg) {
						if(noticeAll.size() > 0) {
							ad_handler.sendEmptyMessage(noticeAll.size());
						}
					}
//				NocticeShow = true;
				}
				
			}
		}
	};
	
	/*
	 * 车险通知
	 */
	Handler ad_handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			AnimationController ac = new AnimationController();
			if(msg.what != noticeAll.size() && msg.what == 0) {
				String notice = "";
				if(noticeAll.get(0).substring(0, 1).equals("年")) {
					notice = " 的年审时间即将到期";
				} else {
					notice = " 的车险时间即将到期";
				}
				first_ad.setText(noticeAll.get(0).subSequence(1, noticeAll.get(0).length()) + notice);
//				lin_cx_ad.setVisibility(View.VISIBLE);
//				first_ad.setVisibility(View.VISIBLE);
//				next_ad.setVisibility(View.GONE);
				
				lin_cx_ad.setVisibility(View.VISIBLE);
				first_ad.setText(noticeAll.get(0).substring(1, noticeAll.get(0).length()) + notice);
				ac.slideInY(first_ad, 800, 0);
				ac.slideOutY(next_ad, 800, 0);
				
			} else if(msg.what != noticeAll.size() && msg.what >= 1) {
				String notice = "";
				if(noticeAll.get(msg.what).substring(0, 1).equals("年")) {
					notice = " 的年审时间即将到期";
				} else {
					notice = " 的车险时间即将到期";
				}
				if(msg.what % 2 != 0) {
					lin_cx_ad.setVisibility(View.VISIBLE);
					next_ad.setText(noticeAll.get(msg.what).substring(1, noticeAll.get(msg.what).length()) + notice);
					ac.slideInY(next_ad, 800, 0);
					ac.slideOutY(first_ad, 800, 0);
				} else {
					lin_cx_ad.setVisibility(View.VISIBLE);
					first_ad.setText(noticeAll.get(msg.what).substring(1, noticeAll.get(msg.what).length()) + notice);
					ac.slideInY(first_ad, 800, 0);
					ac.slideOutY(next_ad, 800, 0);
				}
			} else if(msg.what == noticeAll.size()) {		//结束
				if(noticeAll.size() > 0) {
					
					String notice = "";
					if(noticeAll.get(0).substring(0, 1).equals("年")) {
						notice = " 的年审时间即将到期";
					} else {
						notice = " 的车险时间即将到期";
					}
					if(msg.what % 2 != 0) {
						lin_cx_ad.setVisibility(View.VISIBLE);
						next_ad.setText(noticeAll.get(0).substring(1, noticeAll.get(0).length()) + notice);
						ac.slideInY(next_ad, 800, 0);
						ac.slideOutY(first_ad, 800, 0);
					} else {
						lin_cx_ad.setVisibility(View.VISIBLE);
						first_ad.setText(noticeAll.get(0).substring(1, noticeAll.get(0).length()) + notice);
						ac.slideInY(first_ad, 800, 0);
						ac.slideOutY(next_ad, 800, 0);
					}
				}
			}
			super.handleMessage(msg);
		}
		
	};

	//--------------------------------
	
	public void initView() {
		mCityName = (TextView) findViewById(R.id.mCityName);
		city = SharePrefenceUtil.getCity(this);
		mCityName.setText(city);
		
		lin_cx_ad = (LinearLayout) findViewById(R.id.lin_cx_ad);   
		deleteit = (ImageView) findViewById(R.id.deleteit);
		deleteit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				lin_cx_ad.setVisibility(View.GONE);
				falg = false;
				NocticeShow = true;
			}
		});
		
		first_ad = (TextView) findViewById(R.id.first_ad);
		next_ad = (TextView) findViewById(R.id.next_ad);
//		new Thread(run_ad).start();  TODO
		
		mCityID = (TextView) findViewById(R.id.mCityID);
		city_ID = SharePrefenceUtil.getCityID(this);
		mCityID.setText(city_ID);
		
		home_chose_City = (LinearLayout) findViewById(R.id.home_chose_City);
		home_chose_City.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(ServicesActivity.this, CityListActivity.class);
				intent.putExtra("back", true);
				startActivityForResult(intent, request_city);
			}
		});
		
		findViewById(R.id.top_title_city).findViewById(R.id.left_back).setVisibility(View.INVISIBLE);  //设置返回不可见
		
		allServices = (GridView) findViewById(R.id.allService);
		
		serviceAdapter = new AllServiceAdapter();
		allServices.setAdapter(serviceAdapter);
		
		allServices.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				final KuanterService service = (KuanterService) parent.getAdapter().getItem(position);
//				if(service.getServiceID() != null && !service.getServiceType().equals("")) {
					String str1 = service.getServiceID();
					if(str1.equals(MainConstants.DJ)) {
						Intent dj = new Intent("com.action.dj");
						startActivity(dj);
					} else if(str1.equals(MainConstants.CW)) {	//车务换成年审
						Log.i("bbb", SharePrefenceUtil.getUserID(ServicesActivity.this) + "serv....");
						if(SharePrefenceUtil.checkLogin(ServicesActivity.this)) {
							Intent intent = new Intent("com.action.ns");
							intent.putExtra("cityID", city_ID);
//						Intent intent = new Intent(ServicesActivity.this, AttachExample.class);
							startActivity(intent);
						} else {
							if(HomeActivityGroup.select_id != null) {
								HomeActivityGroup.select_id.add(ProApplication.KUANTER_FW);
							}
							qStartActivity(LoginActivity.class, null, MainConstants.NS_ACTION);
							startActivity_anim(7);
						}
					} else if(str1.equals(MainConstants.QT)) {
						showToast("跳转到其他页面");
					} else if(str1.equals(MainConstants.TH)) {
						Intent intent = new Intent("com.action.myth");
						startActivity(intent);
					} else if(str1.equals(MainConstants.JH)) {
						Intent intent = new Intent(ServicesActivity.this, ActivateCardActivity.class);
						startActivity(intent);
					} else if(str1.equals(MainConstants.CX)) {
						if(!SharePrefenceUtil.checkLogin(ServicesActivity.this)) {
							if(HomeActivityGroup.select_id != null) {
								HomeActivityGroup.select_id.add(ProApplication.KUANTER_FW);
							}
							qStartActivity(LoginActivity.class, null, MainConstants.CX_ACTION);
							startActivity_anim(7);
						} else {
							Intent intent = new Intent("com.action.cx");
							startActivity(intent);
						}
					} else if(str1.equals(MainConstants.LC)) {
						if(!SharePrefenceUtil.checkLogin(ServicesActivity.this)) {
							if(HomeActivityGroup.select_id != null) {
								HomeActivityGroup.select_id.add(ProApplication.KUANTER_FW);
							}
							qStartActivity(LoginActivity.class, null, MainConstants.CX_ACTION);
							startActivity_anim(7);
						} else {
							Intent intent = new Intent("com.action.lc");
							startActivity(intent);
						}
						
					} else if(str1.equals(MainConstants.CZ)) {
						if(!SharePrefenceUtil.checkLogin(ServicesActivity.this)) {
							if(HomeActivityGroup.select_id != null) {
								HomeActivityGroup.select_id.add(ProApplication.KUANTER_FW);
							}
							qStartActivity(LoginActivity.class, null, MainConstants.CZ_ACTION);
							startActivity_anim(7);
						} else {
							Intent intent = new Intent(ServicesActivity.this, RechargeActivity.class);
							startActivity(intent);
						}
					} else {
						String chosed_city = mCityName.getText().toString();
						String typeID = service.getServiceID();
						String serviceID = service.getList_service().get(0).getServiceID();
						final Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
						intent.putExtra("service", service.getList_service().get(0).getServiceName());	//服务名
						intent.putExtra("typeID", typeID);				//服务类型id
						intent.putExtra("serviceID", serviceID);		//具体服务id
						intent.putExtra("localCity", false);			//是否本城市
						intent.putExtra("cityName", chosed_city);			//城市名
						intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
//						startActivity(intent);
						
						if(SharePrefenceUtil.getRotateStatus(ServicesActivity.this) == SharePrefenceUtil.NOTCHOSE) {
							new AlertDialog.Builder(ServicesActivity.this).setItems(R.array.moder, new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									if(which == 0) {
										SharePrefenceUtil.setRotateStatus(ServicesActivity.this, SharePrefenceUtil.MAP);
									} else {
										SharePrefenceUtil.setRotateStatus(ServicesActivity.this, SharePrefenceUtil.LIST);
									}
									
									/*String chosed_city = mCityName.getText().toString();
									String typeID = service.getServiceID();
									String serviceID = service.getList_service().get(0).getServiceID();
									Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
									intent.putExtra("service", service.getList_service().get(0).getServiceName());	//服务名
									intent.putExtra("typeID", typeID);				//服务类型id
									intent.putExtra("serviceID", serviceID);		//具体服务id
									intent.putExtra("localCity", false);			//是否本城市
									intent.putExtra("cityName", chosed_city);			//城市名
									intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点*/	
									
									if(application.locData != null) {
										startActivity(intent);
									} else {
										showProgressLocation("定位中,请稍后...");
										locationDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
											@Override
											public void onCancel(DialogInterface dialog) {
												goToSite = false;
												map.clear();
											}
										});
										map.add(service);
										goToSite = true;
										
										application.startRequest(h);
										h.postDelayed(new Runnable() {
											
											@Override
											public void run() {
												if(goToSite) {
													finishProgressLocation();
													showToast("定位失败");
													goToSite = false;
													map.clear();
												}
											}
										}, 30000);
									}
									
									/*//--
									String chosed_city = mCityName.getText().toString();
//									lc_front = "武汉";  //TODO  .....-----------------------------------------------
									if(!lc_front.equals("")) {
										if(!lc_front.equals(chosed_city)) {
											
											String typeID = service.getServiceID();
											String serviceID = service.getList_service().get(0).getServiceID();
											Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
											intent.putExtra("service", service.getList_service().get(0).getServiceName());	//服务名
											intent.putExtra("typeID", typeID);				//服务类型id
											intent.putExtra("serviceID", serviceID);		//具体服务id
											intent.putExtra("localCity", false);			//是否本城市
											intent.putExtra("cityName", chosed_city);			//城市名
											intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
											startActivity(intent);
											
										} else {
											
											String typeID = service.getServiceID();
											String serviceID = service.getList_service().get(0).getServiceID();
											Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
											intent.putExtra("service", service.getList_service().get(0).getServiceName());
											intent.putExtra("typeID", typeID);
											intent.putExtra("serviceID", serviceID);
											intent.putExtra("cityName", chosed_city);
											intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
											startActivity(intent);
										}
									} else {
//										showToast("定位中,请稍后");
										showProgress("定位中,请稍后...");
										map.add(service);
										goToSite = true;
										progressDialog.setOnDismissListener(new OnDismissListener() {
											@Override
											public void onDismiss(DialogInterface arg0) {
												
											}
										});
										application.startRequest(h);
										h.postDelayed(new Runnable() {
											
											@Override
											public void run() {
												if(goToSite) {
													finishProgress();
													showToast("定位失败");
													goToSite = false;
												}
											}
										}, 30000);
										
//										lc_front = "武汉";   //TODO  要删除掉的
									}*/
									//---
								}
							}).setTitle("优先显示").create().show();
						} else {
							/*String chosed_city = mCityName.getText().toString();
							String typeID = service.getServiceID();
							String serviceID = service.getList_service().get(0).getServiceID();
							Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
							intent.putExtra("service", service.getList_service().get(0).getServiceName());	//服务名
							intent.putExtra("typeID", typeID);				//服务类型id
							intent.putExtra("serviceID", serviceID);		//具体服务id
							intent.putExtra("localCity", false);			//是否本城市
							intent.putExtra("cityName", chosed_city);			//城市名
							intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
*/							
//							startActivity(intent);
							if(application.locData != null) {
								startActivity(intent);
							} else {
								showProgressLocation("定位中,请稍后...");
								locationDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
									@Override
									public void onCancel(DialogInterface dialog) {
										goToSite = false;
										map.clear();
									}
								});
								map.add(service);
								goToSite = true;
								
								application.startRequest(h);
								h.postDelayed(new Runnable() {
									
									@Override
									public void run() {
										if(goToSite) {
											finishProgressLocation();
											showToast("定位失败");
											goToSite = false;
											map.clear();
										}
									}
								}, 30000);
							}
							
							/*//---
							String chosed_city = mCityName.getText().toString();
//							lc_front = "武汉";  //TODO  .....-----------------------------------------------
							if(!lc_front.equals("")) {
								if(!lc_front.equals(chosed_city)) {
									
									String typeID = service.getServiceID();
									String serviceID = service.getList_service().get(0).getServiceID();
									Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
									intent.putExtra("service", service.getList_service().get(0).getServiceName());	//服务名
									intent.putExtra("typeID", typeID);				//服务类型id
									intent.putExtra("serviceID", serviceID);		//具体服务id
									intent.putExtra("localCity", false);			//是否本城市
									intent.putExtra("cityName", chosed_city);			//城市名
									intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
									startActivity(intent);
									
								} else {
									
									String typeID = service.getServiceID();
									String serviceID = service.getList_service().get(0).getServiceID();
									Intent intent = new Intent(ServicesActivity.this,ServiceTurnOver1.class);
									intent.putExtra("service", service.getList_service().get(0).getServiceName());
									intent.putExtra("typeID", typeID);
									intent.putExtra("serviceID", serviceID);
									intent.putExtra("cityName", chosed_city);
									intent.putExtra("center", SharePrefenceUtil.getCenter(ServicesActivity.this)); //中心点
									startActivity(intent);
								}
							} else {
//								showToast("定位中,请稍后");
								showProgress("定位中,请稍后...");
								map.add(service);
								goToSite = true;
								progressDialog.setOnDismissListener(new OnDismissListener() {
									@Override
									public void onDismiss(DialogInterface arg0) {
										
									}
								});
								application.startRequest(h);
								h.postDelayed(new Runnable() {
									
									@Override
									public void run() {
										if(goToSite) {
											finishProgress();
											showToast("定位失败");
											goToSite = false;
										}
									}
								}, 30000);
								
//								lc_front = "武汉";   //TODO  要删除掉的
							}*/
						}
						
						
						
					}
				}
		});
	}
	
	@Override
	protected void onResume() {
		if(application.getList_kuanterService() == null  && status != 0) {
			Log.i("bbb", "重新请求数据");
			serviceAdapter = new AllServiceAdapter();
			allServices.setAdapter(serviceAdapter);
		}
		if(wea_info == null) {
			String cityforweatherID = SharePrefenceUtil.getCityIDForWeather(ServicesActivity.this);
			DataLoader loadWeather = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair nvp = new BasicNameValuePair("cityId",cityforweatherID);
			params.add(nvp);
			loadWeather.DisplayData(MainConstants.HOST_test + HttpConfigAPI.FINDCITYWEATHER, params, wea_handler, "", false);
		}
//		new Thread(new WeaRun("http://m.weather.com.cn/data/" + cityforweatherID + ".html",arg_week)).start();
//		new Thread(new WeaRun("http://www.weather.com.cn/data/sk/" + cityforweatherID + ".html",arg_day)).start();
		status++;
		super.onResume();
	}





	class AllServiceAdapter extends BaseAdapter {
		
		public AllServiceAdapter() {
			List<KuanterService> clone = application.getList_kuanterService();
			if(clone != null) {
				kuanter.addAll(clone);
				KuanterService chongzhi = new KuanterService();
				chongzhi.setServiceType("充值");
				chongzhi.setServiceID(MainConstants.CZ);
				kuanter.add(chongzhi);
				
				KuanterService jh = new KuanterService();
				jh.setServiceType("激活");
				jh.setServiceID(MainConstants.JH);
				kuanter.add(jh);
				
				KuanterService cx = new KuanterService();
				cx.setServiceType("车险");
				cx.setServiceID(MainConstants.CX);
				kuanter.add(cx);
				
				KuanterService lc = new KuanterService();
				lc.setServiceType("理财");
				lc.setServiceID(MainConstants.LC);
				kuanter.add(lc);
				
			} else {
				if(!SharePrefenceUtil.getCityID(ServicesActivity.this).equals("")) {
					showProgress("正在加载数据...");
					DataLoader loader = new DataLoader(ServicesActivity.this);
					List<NameValuePair> params1 = new ArrayList<NameValuePair>();
					NameValuePair cityID = new BasicNameValuePair("cityCode",SharePrefenceUtil.getCityID(ServicesActivity.this));
					params1.add(cityID);
					//TODO
					loader.DisplayData(MainConstants.HOST_test + HttpConfigAPI.FINDSERVICE, params1, h, "", false);
				}
				
				
			}
		}

		@Override
		public int getCount() {
			return kuanter == null ? 0 : kuanter.size();
		}

		@Override
		public Object getItem(int position) {
			return kuanter.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View conview, ViewGroup parent) {
			ViewHolder holder;
			if(conview == null) {
				holder = new ViewHolder();
				conview = factory.inflate(R.layout.service_item, null);
				holder.service_item_text = (TextView) conview.findViewById(R.id.service_item_text);
				holder.service_item_image = (ImageView) conview.findViewById(R.id.service_item_image);
				conview.setTag(holder);
			} else {
				holder = (ViewHolder) conview.getTag();
			}
			
			if(position < 4) {
				if(screenWidth == 480) {
//					conview.setPadding(0, 28, 0, 0);
					conview.setPadding(0, 0, 0, 0);
				} else if(screenWidth == 720) {
					conview.setPadding(0, 0, 0, 0);
				} else if(screenWidth == 540) {
					conview.setPadding(0, 0, 0, 0);
				} else {
					conview.setPadding(0, 0, 0, 0);
				}
			} else {
				conview.setPadding(0, 0, 0, 0);
			}
			holder.service_item_text.setText(kuanter.get(position).getServiceType());
			if(kuanter.get(position).getServiceID().equals(MainConstants.BY)) {
				holder.service_item_image.setImageResource(R.drawable.baoyang);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.CX)) {
				holder.service_item_image.setImageResource(R.drawable.chexian);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.CZ)) {
				holder.service_item_image.setImageResource(R.drawable.chongzhi);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.DJ)) {
				holder.service_item_image.setImageResource(R.drawable.daijia);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.GZ)) {
				holder.service_item_image.setImageResource(R.drawable.gaizhuang);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.JY)) {
				holder.service_item_image.setImageResource(R.drawable.jiuyuan);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.LC)) {
				holder.service_item_image.setImageResource(R.drawable.licai);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.LT)) {
				holder.service_item_image.setImageResource(R.drawable.luantai);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.MR)) {
				holder.service_item_image.setImageResource(R.drawable.meirong);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.CW)) {
				holder.service_item_image.setImageResource(R.drawable.niansheng);
				holder.service_item_text.setText("年审");
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.WX)) {
				holder.service_item_image.setImageResource(R.drawable.weixiu);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.XQ)) {
				holder.service_item_image.setImageResource(R.drawable.xiche);
				holder.service_item_text.setText("洗车网点");
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.DZYQ)) {
				holder.service_item_image.setImageResource(R.drawable.yi_qi);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.YP)) {
				holder.service_item_image.setImageResource(R.drawable.yongpin);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.TH)) {
				holder.service_item_image.setImageResource(R.drawable.youhui);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.QT)) {
				holder.service_item_image.setImageResource(R.drawable.qita);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.JH)) {
				holder.service_item_image.setImageResource(R.drawable.jihuo);
			} else if(kuanter.get(position).getServiceID().equals(MainConstants.CZ)) {
				holder.service_item_image.setImageResource(R.drawable.chongzhi);
			}
			return conview;
		}
		
		class ViewHolder {
			ImageView service_item_image;
			TextView service_item_text;
		}
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == request_city && resultCode == 200) {
			boolean load = data.getBooleanExtra("load", true);
//			if(load) {
			
			showProgress("正在加载数据...");
			city = SharePrefenceUtil.getCity(this);
			mCityName.setText(city);
			city_ID = SharePrefenceUtil.getCityID(this);
			mCityID.setText(city_ID);
			
			DataLoader loader = new DataLoader(ServicesActivity.this);
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			NameValuePair cityID = new BasicNameValuePair("cityCode",SharePrefenceUtil.getCityID(ServicesActivity.this));
			params1.add(cityID);
			//TODO
			loader.DisplayData(MainConstants.HOST_test + "shopInfo/findServiceCategoryOfCity", params1, h, "", false);
			
//			new Thread(new WeaRun("http://m.weather.com.cn/data/" + cityforweatherID + ".html",arg_week)).start();
//			new Thread(new WeaRun("http://www.weather.com.cn/data/sk/" + cityforweatherID + ".html",arg_day)).start();
			String cityforweatherID = SharePrefenceUtil.getCityIDForWeather(ServicesActivity.this);
			DataLoader loadWeather = new DataLoader(this);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			NameValuePair nvp = new BasicNameValuePair("cityId",cityforweatherID);
			params.add(nvp);
			loadWeather.DisplayData(MainConstants.HOST_test + HttpConfigAPI.FINDCITYWEATHER, params, wea_handler, "", false);
			
			//限行信息
			DataLoader loader_xx = new DataLoader(ServicesActivity.this);
			List<NameValuePair> params1_xx = new ArrayList<NameValuePair>();
			NameValuePair cityID_xx = new BasicNameValuePair("cityCode",SharePrefenceUtil.getCityID(ServicesActivity.this));
			params1_xx.add(cityID_xx);
//			TODO
			loader_xx.DisplayData(MainConstants.HOST_test + HttpConfigAPI.findRestriction, params1, restri_handler, "", false);
			
			restriction = null;
			
//			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onClick(View view) {
		
	}
	
	
	class DownBackgroundIamge extends AsyncTask<String, Void, Void> {
		Bitmap bitmap;
		
		@Override
		protected Void doInBackground(String... params) {
			String url = params[0];
			InputStream is = HttpUtil.getStream(url);
			//图片处理
			BitmapFactory.Options option = new BitmapFactory.Options();
            option.inJustDecodeBounds = true;
            
            if(is != null) {
            	bitmap = BitmapFactory.decodeStream(is,null,option);
            	int width = option.outWidth / screenWidth;
            	if(width > 1) {
            		option.inSampleSize = width;
            	} else {
            		width = 1;
            	}
            	option.inJustDecodeBounds = false;
            	
            	InputStream is_1 = HttpUtil.getStream(url);
            	if(is_1 != null) {
            		bitmap = BitmapFactory.decodeStream(is_1, null, option);
            		Matrix matrix = new Matrix();
            		float f_yScale = ((float)100) / option.outHeight;
            		float f_xScale = ((float)screenWidth) /option.outWidth;
            		matrix.postScale(f_xScale, f_yScale);
            		bitmap = Bitmap.createBitmap(bitmap, 0, 0, option.outWidth, option.outHeight,matrix,true);
            		
            		ByteArrayOutputStream baos = new ByteArrayOutputStream();
            		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            		int quality = 100;
            		while(baos.toByteArray().length /1024 > 200) {  //大于200k就压缩
            			baos.reset();
            			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            			quality -= 2;
            		}
            		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            		bitmap = BitmapFactory.decodeStream(bais, null, null);
            		Log.i("bbb", bitmap.getHeight() + "height");
            	}
            }
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			BitmapDrawable db = new BitmapDrawable(bitmap);
			middle_weather_road.setBackgroundDrawable(db);
			super.onPostExecute(result);
		}
		
	}
	
	/*
	 * 得到车险
	 */
	Handler mHandlerVie = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				VehicleInfoList vif = new VehicleInfoList(json);
				List<VehicleInfo> listVi = vif.getVehicleInfoList();
				if(application != null) {
					application.setList_vehicleInfo(listVi);
					
				}
				if(listVi != null) {
					for(int i = 0; i < listVi.size(); i++) {
						VehicleInfo vi = listVi.get(i);
						String endTime_insurance = vi.getInsuranceEndTime();
						if(checkWetherExpire(endTime_insurance,noticeDayInsurance)) {
							noticeAll.add("车" + vi.getLicensePlateNumber());
						}
						
						String endTime_yearChager = vi.getInspectionExpireTime();
						if(checkWetherExpire(endTime_yearChager, noticeDayYearCharge)) {
							noticeAll.add("年" + vi.getLicensePlateNumber());
						}
						
					}
				}
				
				new Thread(run_ad).start();
			}
			super.handleMessage(msg);
		}
		
	};
	
	@Override
	protected void showProgress(String message) {
		progressDialog = new ProgressDialog(ServicesActivity.this);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setCancelable(false);
		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progressDialog.setMessage(message);
		progressDialog.show();
	}
	
	ProgressDialog locationDialog;
	protected void showProgressLocation(String message) {
		locationDialog = new ProgressDialog(ServicesActivity.this);
		locationDialog.setCanceledOnTouchOutside(false);
		locationDialog.setCancelable(true);
		locationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		locationDialog.setMessage(message);
		locationDialog.show();
	}
	
	protected void finishProgressLocation() {
		if (locationDialog != null) {
			locationDialog.dismiss();
			locationDialog=null;
		}
	}
	
	
	/**
	 * 结束进度框
	 * 
	 * @param progress
	 */
	@Override
	protected void finishProgress() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog=null;
		}
	}
	
	public boolean checkWetherExpire(String endTime,int expireTime) {
		boolean flag = false;
		if(endTime != null && !endTime.equals("") && !endTime.equals("null")) {
			
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date endDate = df.parse(endTime);
				Date now = new Date();
				long diff = endDate.getTime() - now.getTime();
				long day = diff / (1000 * 60 * 60 * 24);
				if(day < expireTime && day >= 0) {
					flag = true;
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}
		return flag;
	}
	
	class WeaRun implements Runnable {
		String url;
		int arg;
		public WeaRun(String url,int arg) {
			this.url = url;
			this.arg = arg;
		}

		@Override
		public void run() {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet(url);
			try {
				HttpResponse response = client.execute(request);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					HttpEntity entity = response.getEntity();
					String result = EntityUtils.toString(entity);
					Message msg = wea_handler.obtainMessage();
					msg.what = HttpTask.RESULT_OK;
					msg.obj = result;
					msg.arg1 = arg;
					wea_handler.sendMessage(msg);
					Log.i("bbb", result);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
